/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkFile, ts, AstTreeUtils } from "arkanalyzer";
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from "../BaseChecker";
import { FileMatcher, MatcherCallback, MatcherTypes } from '../../Index';
import { Defects, IssueReport } from "../../model/Defects";
import { Rule } from "../../model/Rule";
import { RuleListUtil } from "../../utils/common/DefectsList";

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'ExplicitFunctionReturnTypeCheck');
const gMetaData: BaseMetaData = {
    severity: 1,
    ruleDocPath: "docs/explicit-function-return-type-check.md",
    description: "Require explicit return types on functions and class methods",
};
const defaultOptions: Options = {
    allowExpressions: false,
    allowTypedFunctionExpressions: true,
    allowHigherOrderFunctions: true,
    allowDirectConstAssertionInArrowFunctions: true,
    allowConciseArrowFunctionExpressionsStartingWithVoid: false,
    allowFunctionsWithoutTypeParameters: false,
    allowedNames: [],
    allowIIFEs: false,
}
interface Options {
    /** Whether to allow arrow functions that start with the `void` keyword. */
    allowConciseArrowFunctionExpressionsStartingWithVoid?: boolean;
    /** Whether to ignore arrow functions immediately returning a `as const` value. */
    allowDirectConstAssertionInArrowFunctions?: boolean;
    /** Whether to ignore function expressions (functions which are not part of a declaration). */
    allowExpressions?: boolean;
    /** Whether to ignore functions that don't have generic type parameters. */
    allowFunctionsWithoutTypeParameters?: boolean;
    /** Whether to ignore functions immediately returning another function expression. */
    allowHigherOrderFunctions?: boolean;
    /** Whether to ignore immediately invoked function expressions (IIFEs). */
    allowIIFEs?: boolean;
    /** Whether to ignore type annotations on the variable of function expressions. */
    allowTypedFunctionExpressions?: boolean;
    /** An array of function/method names that will not have their arguments or return values checked. */
    allowedNames?: string[];
}

// 定义一个接口，用于存储函数或方法的行列信息
interface LocationInfo {
    fileName: string;
    line: number;
    character: number;
    description: string;
}

export class ExplicitFunctionReturnTypeCheck implements BaseChecker {

    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];
    private fileMatcher: FileMatcher = {
        matcherType: MatcherTypes.FILE,
    };

    public registerMatchers(): MatcherCallback[] {
        const fileMatcherCb: MatcherCallback = {
            matcher: this.fileMatcher,
            callback: this.check
        }
        return [fileMatcherCb];
    }

    public check = (target: ArkFile) => {
        if (target instanceof ArkFile) {
            const targetName = target.getName();
            if (targetName && this.getFileExtension(targetName) === ".ets") {
                return;
            }
            const code = target.getCode();
            if (!code) {
                return;
            }
            const filePath = target.getFilePath();
            const sourceFile = AstTreeUtils.getASTNode(target.getName(), code);
            const missingReturnTypes = this.checkExplicitReturnType(sourceFile);
            missingReturnTypes.forEach(info => {
                this.addIssueReportNode(info, filePath);
            });
        }
    }

    private getFileExtension(filePath: string): string {
        const lastDotIndex = filePath.lastIndexOf('.');
        if (lastDotIndex === -1) {
            return '';
        }
        return filePath.substring(lastDotIndex);
    }


    public checkExplicitReturnType(sourceFile: ts.SourceFile): LocationInfo[] {
        const result: LocationInfo[] = [];
        const Options: Options = this.rule && this.rule.option[0] ? this.rule.option[0] as Options : defaultOptions;

        const visit: (node: ts.Node) => void = (node: ts.Node) => {
            // 特殊情况处理
            if (Options.allowDirectConstAssertionInArrowFunctions && ts.isArrowFunction(node) && ts.isDeleteExpression(node)) {
                return;
            }
            if (Options.allowExpressions && ts.isArrowFunction(node)) {
                return;
            }
            if (Options.allowTypedFunctionExpressions && ts.isTypeOfExpression(node)) {
                return;
            }
            if (Options.allowConciseArrowFunctionExpressionsStartingWithVoid && ts.isVoidExpression(node)) {
                return;
            }
            if (Options.allowIIFEs && ts.isArrowFunction(node) && ts.isPrefixUnaryExpression(node) && ts.isPostfixUnaryExpression(node)) {
                return;
            }
            // 检查函数声明
            if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
                if (Options.allowFunctionsWithoutTypeParameters && !node.typeParameters) {
                    return;
                }
                this.checkFunctionDeclaration(node, sourceFile, Options, result);
            }
            if (ts.isVariableDeclaration(node)) {
                this.checkVariableDeclaration(node, sourceFile, Options, result);
            }
            ts.forEachChild(node, visit);
        };

        visit(sourceFile);
        return result;
    }

    // 辅助函数：判断函数是否有显式的返回类型注解
    private hasExplicitReturnType(node: ts.FunctionDeclaration | ts.MethodDeclaration): boolean {
        // 如果函数有返回类型注解，或者函数体中返回的是一个有明确类型的函数，则返回 true
        if (node.type) {
            return true; // 显式返回类型注解
        }

        // 如果函数体中返回的是一个函数表达式或箭头函数，检查其是否有类型注解
        if (!node.body) {
            return false;
        }
        for (const statement of node.body.statements) {
            if (ts.isReturnStatement(statement) && statement.expression) {
                if (ts.isFunctionExpression(statement.expression) || ts.isArrowFunction(statement.expression)) {
                    return !!statement.expression.type; // 返回的函数有类型注解
                }
            }
        }
        return false;
    }

    private hasAsExpression(node: ts.FunctionDeclaration | ts.MethodDeclaration
        | ts.FunctionExpression | ts.ArrowFunction): boolean {
        if (!node.body) {
            return false;
        }
        // 检查函数体是否是一个块（Block）
        if (ts.isBlock(node.body)) {
            for (const statement of node.body.statements) {
                // 检查是否是 return 语句
                if (ts.isReturnStatement(statement) && statement.expression && ts.isAsExpression(statement.expression)) {
                    // 检查返回值是否是一个 AsExpression
                    return true;
                }
            }
        }

        // 检查函数体是否是一个表达式（例如箭头函数的简写形式）
        if (!ts.isBlock(node.body)) {
            // 直接检查表达式是否是一个 AsExpression
            if (ts.isAsExpression(node.body)) {
                return true;
            }
        }

        return false;
    }

   // 检查函数声明是否符合显式类型要求。
    private checkFunctionDeclaration(
        node: ts.FunctionDeclaration | ts.MethodDeclaration,
        sourceFile: ts.SourceFile,
        Options: Options,
        result: LocationInfo[]
    ): void {
        // 检查函数是否被导出
        if (node.body && this.hasAsExpression(node) && Options.allowDirectConstAssertionInArrowFunctions) {
            return;

        }
        // 检查返回类型注解
        if (!node.type) {

            // 如果函数返回的是另一个函数，且返回的函数有明确的类型注解，则不报错
            if (!node.body || !this.hasExplicitReturnType(node)) {
                this.addIssue(result, sourceFile, node.getStart(),
                    'Missing return type on function.');
            }
        }
    }

    private checkVariableDeclaration(
        node: ts.VariableDeclaration,
        sourceFile: ts.SourceFile,
        Options: Options,
        result: LocationInfo[]
    ): void {
        const initializer = node.initializer;
        if (initializer && (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer))) {
            if (!initializer.type) {
                if (Options.allowDirectConstAssertionInArrowFunctions && this.hasAsExpression(initializer)) {
                    return;
                }
                let startNumber = initializer.getStart();
                if (ts.isArrowFunction(initializer)) {
                    startNumber = initializer.equalsGreaterThanToken?.getStart();
                }
                this.addIssue(result, sourceFile, startNumber,
                    'Missing return type on function.');
            }
        }
        if (initializer && ts.isObjectLiteralExpression(initializer)) {
            this.checkObjectLiteralExpression(initializer, sourceFile, Options, result);
        }
    }

    private checkObjectLiteralExpression(
        initializer: ts.ObjectLiteralExpression,
        sourceFile: ts.SourceFile,
        Options: Options,
        result: LocationInfo[]
    ): void {
        // 遍历对象字面量的属性
        for (const property of initializer.properties) {
            if (ts.isPropertyAssignment(property)) {
                this.checkObjectLiteralExpressionProperty(property, sourceFile, Options, result);
            }
        }
    }
    
    private checkObjectLiteralExpressionProperty(
        property: ts.PropertyAssignment,
        sourceFile: ts.SourceFile,
        Options: Options,
        result: LocationInfo[]
    ): void {
        const name = property.name;
        const value = property.initializer || property;
        // 检查属性值是否为函数表达式或箭头函数
        if (value && (ts.isFunctionExpression(value) || ts.isArrowFunction(value))) {
            const func = value as ts.FunctionExpression | ts.ArrowFunction;

            // 检查函数表达式的返回类型注解
            if (!func.type && !Options.allowTypedFunctionExpressions) {
                this.addIssue(result, sourceFile, func.parent.getStart(),
                    'Missing return type on function.');
            }
        }
    }

    /**
    * 添加问题报告。
    */
    private addIssue(
        result: LocationInfo[],
        sourceFile: ts.SourceFile,
        pos: number,
        description: string
    ): void {
        const { line, character } = sourceFile.getLineAndCharacterOfPosition(pos);
        result.push({
            fileName: sourceFile.fileName,
            line: line + 1,
            character: character + 1,
            description: description,
        });
    }

    private addIssueReportNode(loc: LocationInfo, filePath: string): void {
        const severity = this.rule.alert ?? this.metaData.severity;
        if (loc.description) {
            this.metaData.description = loc.description;
        }
        let defect = new Defects(loc.line, loc.character, loc.character, this.metaData.description, severity,
            this.rule.ruleId, filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defect, undefined));
        RuleListUtil.push(defect);
    }
}

